<?php
class Message extends CI_Controller{
	
	function index($recipient = NULL){
		/*
		 * Open inbox
		 */
		include("authenticate.php");
		
		$this->load->model('message_model');
		
		//get messages of logged in user
		if(isset($_SESSION['username'])){
			$data['messages'] = (array)$this->message_model->getMessageOf($_SESSION['username']);
		}
		
		//used to generate notification when user had sent a message
		if(isset($recipient)){
			$data['recipient'] = $recipient;
		}
		
		$this->load->view('view_inbox', $data);
	}
	
	function sendMessage(){
		/*
		 * Validate message and save to database
		 */
		 
		include("authenticate.php");
		
		$this -> load -> model('message_model');
		$this -> load -> library('form_validation');
		
		//validation rules
		$this -> form_validation -> set_rules('username', 'username', 'required|callback_usernameCheck');
		$this -> form_validation -> set_rules('title', 'message title', 'required|max_length[20]');
		$this -> form_validation -> set_rules('content', 'content', 'required');
		
		if ($this -> form_validation -> run() == FALSE) {
			
			//redirect to form
			$this -> load -> view('view_create_message');

		} else {
			//save to db
			$senderUsername = $this->input->post('user_username');
			$recipient = $this->input->post('username');
			$content = $this->input->post('content');
			$title = $this->input->post('title');
			$date = date("Y-m-d H:i:s");
			
			$data = array(
				'sender_username' => $senderUsername,
				'recipient_username' => $recipient,
				'message_title' => $title,
				'message_content' => $content,
				'message_date' => $date
			);
			
			$this->load->model('message_model');
			$result = $this->message_model->addMessage($data);
			
			if($result == 1){
				//open inbox and show notification				
				$this->index($recipient);
			}else{
				echo "error";
			}
		}
	}
	
	function delete(){
		/*
		 * Delete a message from database
		 */
		 
		$this->load->model('message_model');
		$id = $this->input->post('message_id');
		$this->message_model->deleteMessage($id);

	}
	
	function view($id = NULL){
		/*
		 * Open a message
		 */
		include("authenticate.php");
		
		if($id === NULL){
			//if id is null
			show_404(base_url());
		}else{
			//show the message
			$this->load->model('message_model');
			$data['message'] = $this->message_model->getMessageById($id);
			$this->load->view('view_message', $data);
		}
	}
	
	function usernameCheck($username){
		/*
		 * Used to validate whether a valid recipent's username exist
		 */
		$this->form_validation->set_message('usernameCheck', 'Username does not exist!');
		
		$this -> load -> model('user_model');
		
		$result = $this->user_model->check_username($username);
		
		return $result;
	}
	
}
?>